package ext.acae2.statements;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;

import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.Quantity;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTRuntimeException;
import wt.vc.views.ViewHelper;
import ext.acae2.statements.bean.PartsCatalogBean;
import ext.acae2.util.IBAUtil;

public class PartsCatalog {

	private static final Logger LOGGER = LogR.getLogger(PartsCatalog.class.getName());
	
	public static void download(WTPart part, OutputStream output) 
            throws WTRuntimeException, WTException, IOException {
        LOGGER.debug("> Start download");
        
        String wthome = (String) WTProperties.getLocalProperties().get("wt.home");
        
        File templateFile = new File(wthome + File.separator 
                + "codebase" + File.separator + "ext" + File.separator 
                + "acae2" + File.separator + "conf" + File.separator
                + "PartsCatalog.xls");
        
        List<PartsCatalogBean> partsCatalogList = new ArrayList<PartsCatalogBean>();
        creatPartsCatalogBean(part, partsCatalogList);
        
        for (PartsCatalogBean partsCatalog : partsCatalogList) {
        	selectAll(partsCatalog, partsCatalogList, Long.valueOf(partsCatalog.getParentPartQuantity()));
        }
        
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(templateFile));
        HSSFSheet sheet = workbook.getSheetAt(0);

        HSSFCellStyle seqCst = workbook.createCellStyle();
		seqCst.setBorderTop(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderRight(HSSFCellStyle.BORDER_THIN);
		seqCst.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        
        int rowNum = 4;
        write(partsCatalogList, rowNum, sheet, seqCst, part.getContainerName());
        
        workbook.write(output);
        output.flush();
        output.close();
        
        LOGGER.debug("> End download");
    }
	
	private static void creatPartsCatalogBean(WTPart part, List<PartsCatalogBean> partsCatalogList) throws RemoteException, WTException{
		
//		if (part.getState().toString().equals("RELEASED")) {
			
			WTPartStandardConfigSpec standardConfigSpec = WTPartStandardConfigSpec
					.newWTPartStandardConfigSpec(
							ViewHelper.service.getView("Design"), null);
			WTPartConfigSpec configSpec = WTPartConfigSpec
					.newWTPartConfigSpec(standardConfigSpec);
			
			QueryResult childPartsQs = WTPartHelper.service.getUsesWTParts(part, configSpec);
			while (childPartsQs.hasMoreElements()) {
				PartsCatalogBean partsCatalogBean = new PartsCatalogBean();
				partsCatalogBean.setParentPartNumber(part.getNumber());
				
				Object obj[] = null;
				obj = (Object[]) childPartsQs.nextElement();
				if (obj[1] instanceof WTPart) {
					WTPart childPart = (WTPart) obj[1];
							
					WTPartUsageLink alink = (WTPartUsageLink) obj[0];
					Quantity quantity = alink.getQuantity();
							
					double singleQuantity = quantity.getAmount();
					String singleStrForParent = String.valueOf(singleQuantity).substring(0,String.valueOf(singleQuantity).lastIndexOf(".")).toString();
						
					partsCatalogBean.setNumber(childPart.getNumber());
					partsCatalogBean.setName(childPart.getName());
					IBAUtil iba = new IBAUtil(childPart);
					
					String characterType = "";
					if(iba.getIBAValue("characterType") != null){
						characterType = iba.getIBAValue("characterType");
					}
					
					if(characterType.equals("关键件")){
						characterType = "G";
					}else if(characterType.equals("重要件")){
						characterType = "Z";
					}
					
					partsCatalogBean.setCharacterType(characterType);
					partsCatalogBean.setVersion(childPart.getVersionIdentifier().getValue());
					partsCatalogBean.setParentPartQuantity(singleStrForParent);
					String material = iba.getIBAValue("material") + " " + iba.getIBAValue("materialStandard");
					partsCatalogBean.setMaterial(material.replaceAll("null", ""));
					
//					if(childPart.getState().toString().equals("RELEASED")){
						if((childPart.getNumber().length() == 13 && childPart.getNumber().substring(10,11).equals("M")) || (childPart.getNumber().length() == 13 && childPart.getNumber().substring(10,11).equals("G"))){
							creatPartsCatalogBean(childPart, partsCatalogList);
						}else{
							partsCatalogList.add(partsCatalogBean);
						}
//					}
				}
			}
//		}
	}
	
	@SuppressWarnings({ "deprecation", "unchecked" })
	private static void write(List<PartsCatalogBean> partsCatalogList, int rowNum, HSSFSheet sheet, HSSFCellStyle seqCst, String containerName){
		
		HSSFRow containerRow = sheet.createRow(1);
		containerRow.createCell(1);
		containerRow.getCell(1).setCellStyle(seqCst);
		containerRow.createCell(9).setCellValue(containerName);
		containerRow.getCell(9).setCellStyle(seqCst);
		
		String number = "";
		String name = "";
		String quantity = "";
		String characterType = "";
		String version = "";
		
		Collections.sort(partsCatalogList);
		
		for (PartsCatalogBean partsCatalog : partsCatalogList) {
			HSSFRow row = sheet.createRow(rowNum);
            
			sheet.addMergedRegion(new Region(rowNum,(short)1,rowNum,(short)2)); 
			
			HSSFRow row1 = sheet.getRow(rowNum-1);
			
			// 零件号
            if(row1.getCell(0).getStringCellValue().equals(partsCatalog.getNumber()) || (row1.getCell(0).getStringCellValue() == "" && number.equals(partsCatalog.getNumber()))){
            	row.createCell(0).setCellValue("");
            }else{
            	row.createCell(0).setCellValue(partsCatalog.getNumber());
            }
            
            // 零件名称
            if((row1.getCell(1).getStringCellValue().equals(partsCatalog.getName()) && number.equals(partsCatalog.getNumber())) || (row1.getCell(1).getStringCellValue() == "" && name.equals(partsCatalog.getName()) && number.equals(partsCatalog.getNumber()))){
            	row.createCell(1).setCellValue("");
            }else{
            	row.createCell(1).setCellValue(partsCatalog.getName());
            }
            
            // 每台数量
            if((row1.getCell(3).getStringCellValue().equals(partsCatalog.getQuantity()) && number.equals(partsCatalog.getNumber())) || (row1.getCell(3).getStringCellValue() == "" && quantity.equals(partsCatalog.getQuantity()) && number.equals(partsCatalog.getNumber()))){
            	row.createCell(3).setCellValue("");
            }else{
            	row.createCell(3).setCellValue(partsCatalog.getQuantity());
            }
            
            // 标记
            if((row1.getCell(4).getStringCellValue().equals(partsCatalog.getCharacterType()) && number.equals(partsCatalog.getNumber())) || (row1.getCell(4).getStringCellValue() == "" && characterType.equals(partsCatalog.getCharacterType()) && number.equals(partsCatalog.getNumber()))){
            	row.createCell(4).setCellValue("");
            }else{
            	row.createCell(4).setCellValue(partsCatalog.getCharacterType());
            }
            
            // 版本
            if((row1.getCell(5).getStringCellValue().equals(partsCatalog.getVersion()) && number.equals(partsCatalog.getNumber())) || (row1.getCell(5).getStringCellValue() == "" && version.equals(partsCatalog.getVersion()) && number.equals(partsCatalog.getNumber()))){
            	row.createCell(5).setCellValue("");
            }else{
            	row.createCell(5).setCellValue(partsCatalog.getVersion());
            }
			
            // 装配处
            // 组件号
            row.createCell(6).setCellValue(partsCatalog.getParentPartNumber());
            // 数量
            row.createCell(7).setCellValue(partsCatalog.getParentPartQuantity());
            // 材料
            row.createCell(8).setCellValue(partsCatalog.getMaterial());
            
            number = partsCatalog.getNumber();
            name = partsCatalog.getName();
            quantity = partsCatalog.getQuantity();
            characterType = partsCatalog.getCharacterType();
            version = partsCatalog.getVersion();
            
            rowNum++;
		}
	}
	
	private static void selectAll(PartsCatalogBean partsCatalog, List<PartsCatalogBean> partsCatalogList, Long l){
		for (PartsCatalogBean partsCatalog1 : partsCatalogList) {
			if(partsCatalog1.getNumber().equals(partsCatalog.getParentPartNumber())){
				l = Long.valueOf(partsCatalog1.getParentPartQuantity()) * l;
				selectAll(partsCatalog1, partsCatalogList, l);
			}
			partsCatalog.setQuantity(l+"");
    	}
	}
	
}
